#include "stdafx.h"
#include "ipfetcher.h"
#include <QtCore>
#include <QtNetwork>
#include "common.h"

#pragma pack ( 1 )

struct ClientString
{
	int length;
	char data[1]; //[length];
}PACKED();

struct DataStruct
{
	unsigned	short magic; // 0x2382
	unsigned	char operaction; // 0x05 for fetch ip
    int		unknow1_1;
    int		unknow1_2;
    int		unknow2_1;
    int		unknow2_2;
    int		unknow3_1;
    int		unknow3_2;
	// ClientString structureArray;
}PACKED();


QHostAddress fetchIP ()
{
	QUdpSocket s;

	/* the data struction is specificed in DataStruct structure*/
	unsigned char data[] = {
		0x82 , 0x23 , 0x05 };

	/* the size to send must be 500 */
	s.writeDatagram ( (char *)data , 500 , QHostAddress ( "202.193.160.123" ) , 5301 );

	/* try to recieve the data*/
	char recvBuff[1024];
    unsigned int recved = 0;

	QTime start = QTime::currentTime ();
	{
		do
		{
			ushort port = 5201;
            QHostAddress anyAddress( QHostAddress::Any );
			int size = s.readDatagram ( recvBuff + recved ,
										sizeof (recvBuff)-recved ,
                                        &anyAddress ,
										&port );
			if ( size != -1 )
			{
				recved += size;
			}
		} while ( start.msecsTo ( QTime::currentTime () ) < 1500 && recved < 500 );
	}
	
	if ( recved <= sizeof ( DataStruct ) )
		return QHostAddress ();

	/* analys the data recived */
	char *stringStart = &recvBuff[sizeof ( DataStruct )];
	ClientString *struction;
	QHostAddress addr;

	for ( int i = 0; i < 4 && !addr.toIPv4Address (); i++ , stringStart = stringStart + struction->length + 4 )
	{
		struction = (ClientString *)stringStart;
		char str[1024];
		strncpy ( str , struction->data , struction->length );
		str[struction->length] = 0;
		addr = QHostAddress ( str );
	}
	return addr;
}
